﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
using System.Windows.Media.Animation;

namespace WpfApplication2
{
    /// <summary>
    /// Interaction logic for DeploymentPropertyWindow.xaml
    /// </summary>
    public partial class DeploymentPropertyWindow : UserControl
    {
        Entities.DeploymentProperty ProductionProperty;
        Entities.DeploymentProperty StagingProperty;
        ServiceController.ServiceController serviceController;
        String ServiceName;
        public DeploymentPropertyWindow(Entities.DeploymentProperty _ProductionProperty, Entities.DeploymentProperty _StagingProperty,String _ServiceName)
        {
            InitializeComponent();
            ServiceName = _ServiceName;
            ProductionProperty= _ProductionProperty;
            StagingProperty = _StagingProperty;
            serviceController = new ServiceController.ServiceController();
            serviceController.GetDeploymentPropertyComplete += new ServiceController.ServiceControllerEventHandler(serviceController_GetDeploymentPropertyComplete);
            serviceController.UpdateDeploymentStatusComplete += new ServiceController.ServiceControllerEventHandler(serviceController_UpdateDeploymentStatusComplete);
            serviceController.DeleteDeploymentComplete += new ServiceController.ServiceControllerEventHandler(serviceController_DeleteDeploymentComplete);
            serviceController.SwapComplete += new ServiceController.ServiceControllerEventHandler(serviceController_SwapComplete);
            this.Loaded += new RoutedEventHandler(DeploymentPropertyWindow_Loaded);
        }
        int GetDeploymentCount;
        string RequestID;
        private Storyboard startbusy;
        private Storyboard stopbusy;

        public DeploymentPropertyWindow(String _ServiceName)
        {
            InitializeComponent();
            serviceController = new ServiceController.ServiceController();
            serviceController.GetDeploymentPropertyComplete += new ServiceController.ServiceControllerEventHandler(serviceController_GetDeploymentPropertyComplete);
            serviceController.UpdateDeploymentStatusComplete += new ServiceController.ServiceControllerEventHandler(serviceController_UpdateDeploymentStatusComplete);
            serviceController.DeleteDeploymentComplete += new ServiceController.ServiceControllerEventHandler(serviceController_DeleteDeploymentComplete);
            serviceController.SwapComplete += new ServiceController.ServiceControllerEventHandler(serviceController_SwapComplete);
            serviceController.GetOperationStatusComplete += new ServiceController.ServiceControllerEventHandler(serviceController_GetOperationStatusComplete);
            serviceController.GetHostServicePropertyCompleted += new ServiceController.ServiceControllerEventHandler(serviceController_GetHostServicePropertyCompleted);
            ServiceName = _ServiceName;
            this.Loaded+=new RoutedEventHandler(DeploymentPropertyWindow_Loaded);
            GetDeploymentCount = 0;
            startbusy = (Storyboard)this.FindResource("StartBusy");
            stopbusy = (Storyboard)this.FindResource("StopBusy");
        }

        void serviceController_GetHostServicePropertyCompleted(object sender, ServiceController.ServiceControllerEventArgs e)
        {
            this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)(() =>
            {
                if (e.IsOperationSuccessful)
                {
                    Entities.DeploymentProperty dp = new Entities.DeploymentProperty();

                    List<Entities.DeploymentProperty> list=new List<Entities.DeploymentProperty>();
                    TextBlockProductionStatus.Text = "";
                    TextBlockStagingStatus.Text = "";

                    for (int i = 0; i < e.HostServiceProperty.DeploymentPropertyList.Count; i++)
                    {

                        if (e.HostServiceProperty.DeploymentPropertyList[i].DeploymentSlot.Equals("Staging"))
                        {
                            TextBlockStagingStatus.Text = e.HostServiceProperty.DeploymentPropertyList[i].Status;
                            StagingProperty = e.HostServiceProperty.DeploymentPropertyList[i];
                        }
                        else 
                        {
                            TextBlockProductionStatus.Text = e.HostServiceProperty.DeploymentPropertyList[i].Status;
                            ProductionProperty = e.HostServiceProperty.DeploymentPropertyList[i];
                        }
                    }

                    


                }

            }));
        }

        void serviceController_GetDeploymentPropertyComplete(object sender, ServiceController.ServiceControllerEventArgs e)
        {
            this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)(() =>
            {
                lock (this)
                {
                    GetDeploymentCount++;
                }
                if (e.IsOperationSuccessful)
                {
                    if (e.DeploymentProperty.DeploymentSlot.Equals("Staging"))
                    {
                        StagingProperty = e.DeploymentProperty;

                        SetStagingDeploymentProperty();

                    }
                    else
                    {
                        ProductionProperty = e.DeploymentProperty;
                        SetProductionDeploymentProperty();

                    }
                }
                else
                {
                    if ((Boolean)e.UserState)
                    {
                        ProductionProperty = null;
                        SetProductionDeploymentProperty();
                    }
                    else
                    {
                        StagingProperty = null;
                        SetStagingDeploymentProperty();
                    }
                }
                if (GetDeploymentCount == 2)
                {
                    HideMask();
                    GetDeploymentCount = 0;
                    if (StagingProperty != null && ProductionProperty != null)
                    {
                        ButtonSwap.Visibility = Visibility.Visible;
                    }
                }

            }));
        }
        
        void serviceController_GetOperationStatusComplete(object sender, ServiceController.ServiceControllerEventArgs e)
        {
            this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)(() =>
            {
                if (!e.IsOperationSuccessful)
                {
                    MessageBox.Show(e.error.Message,"Error",MessageBoxButton.OK,MessageBoxImage.Error);

                }
                else
                {
                    MessageBox.Show(e.OperationStatus.Status);
                }
            }));
        }

        void serviceController_SwapComplete(object sender, ServiceController.ServiceControllerEventArgs e)
        {
            this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)(() =>
            {
                HideMask();
                if (e.error != null)
                {
                    MessageBox.Show(e.error.Message,"Error",MessageBoxButton.OK,MessageBoxImage.Error);

                }
                else
                {

                    MessageBox.Show("Swap operation completed successfully.","Information",MessageBoxButton.OK,MessageBoxImage.Information );
                    LoadProperties();
                }
            }));
        }

        void serviceController_DeleteDeploymentComplete(object sender, ServiceController.ServiceControllerEventArgs e)
        {
            this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)(() =>
           {
               HideMask();
               if (e.error != null)
               {
                   MessageBox.Show(e.error.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);

               }
               else
               {

                   MessageBox.Show("Deployment deleted successfully.","Information",MessageBoxButton.OK,MessageBoxImage.Information);
                   LoadProperties();
               }
           }));
        }

        void serviceController_UpdateDeploymentStatusComplete(object sender, ServiceController.ServiceControllerEventArgs e)
        {
            this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)(() =>
           {
               HideMask();

               if (e.error != null)
               {
                   MessageBox.Show(e.error.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                   
               }
               else
               {
                   MessageBox.Show("Deployment status updated successfully.", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                   LoadProperties();
                   //if (e.RequestID != null)
                   //{
                   //    serviceController.GetOperationStatusAsync(App.SubscriptionID, App.CertificatePath, e.RequestID, null);
                   //}
                   //else
                   //{
                   //    MessageBox.Show("Deployment Status Updated Successfully");
                   //}
               }
           }));
        }

        void DeploymentPropertyWindow_Loaded(object sender, RoutedEventArgs e)
        {

            LoadProperties();
            //SetProductionDeploymentProperty();
            //SetStagingDeploymentProperty();
       }

        private void LoadProperties()
        {
            ShowMask();
            //serviceController.GetHostServicePropertyAsync(App.SubscriptionID, App.CertificatePath, ServiceName, true, null);
            serviceController.GetDeploymentPropertyAsync(App.SubscriptionID, App.CertificatePath, ServiceName, "Production", true);
            serviceController.GetDeploymentPropertyAsync(App.SubscriptionID, App.CertificatePath, ServiceName, "Staging", false);

        }

        private void SetStagingDeploymentProperty()
        {
            if (StagingProperty != null)
            {
                if (StagingProperty.Status.Equals("Running"))
                {
                    ButtonStagingStatus.Content = "Suspend";
                    BtnStagingDelete.IsEnabled = false;
                }
                if (StagingProperty.Status.Equals("Suspended"))
                {
                    ButtonStagingStatus.Content = "Run";
                    BtnStagingDelete.IsEnabled = true;

                  
                }
                DataGridStagingRoleList.ItemsSource = StagingProperty.RoleInstanceList;

                if (StagingProperty.Url != null)
                {
                    TextBoxStagingURL.Text = StagingProperty.Url;
                    Uri uri = new Uri(StagingProperty.Url);
                    LinkStaging.NavigateUri = uri;
                }
                TextBlockStagingID.Text = StagingProperty.PrivateID;
                TextBlockStagingDeploymentName.Text = StagingProperty.Name;
                ImageStaging.Source = new BitmapImage(new Uri("/WpfApplication2;component/images/DeployPic.jpg", UriKind.Relative));
                TextBlockStagingStatus.Text = StagingProperty.Status;
                //TextBoxStagingLabel.Text = HelperClass.ConvertBase64toString(StagingProperty.Label);
                TextBoxStagingLabel.Text = StagingProperty.Label;
                ButtonStagingDeploy.Visibility = Visibility.Visible;
                ButtonStagingStatus.Visibility = Visibility.Visible;
                BtnStagingDelete.Visibility = Visibility.Visible;
                BtnStagingConfigure.Visibility = Visibility.Visible;
                BtnStagingCreateDeploy.Visibility = Visibility.Collapsed;
                BtnStagingRefresh.Visibility = Visibility.Visible;
            }
            else
            {

                //ImageStaging.Source = null;
                ImageStaging.Source = new BitmapImage(new Uri("/WpfApplication2;component/images/CreateDeploy.jpg", UriKind.Relative));

                TextBoxStagingURL.Text = "";
                TextBlockStagingDeploymentName.Text = "";
                TextBlockStagingStatus.Text = "";
                TextBlockStagingID.Text = "";
                
                TextBoxStagingLabel.Text = "";
                DataGridStagingRoleList.ItemsSource = null;
                ButtonSwap.Visibility = Visibility.Collapsed;
                ButtonStagingDeploy.Visibility = Visibility.Collapsed;
                ButtonStagingStatus.Visibility = Visibility.Collapsed;
                BtnStagingDelete.Visibility = Visibility.Collapsed;
                BtnStagingConfigure.Visibility = Visibility.Collapsed;
                BtnStagingCreateDeploy.Visibility = Visibility.Visible;
                BtnStagingRefresh.Visibility = Visibility.Collapsed;
                
                
                
            }
           
        }

        private void SetProductionDeploymentProperty()
        {
            if (ProductionProperty != null)
            {
                if (ProductionProperty.Status.Equals("Running"))
                {
                    BtnProductionDelete.IsEnabled = false;
                    ButtonProductionStatus.Content = "Suspend";
                }
                if (ProductionProperty.Status.Equals("Suspended"))
                {
                    ButtonProductionStatus.Content = "Run";
                    BtnProductionDelete.IsEnabled = true;
                }
                DataGridProductionRoleList.ItemsSource = ProductionProperty.RoleInstanceList;
                if (ProductionProperty.Url != null)
                {
                    TextBoxProductionURL.Text = ProductionProperty.Url;
                    Uri uri = new Uri(ProductionProperty.Url);
                    LinkProduction.NavigateUri = uri;
                }
                TextBlockProductionID.Text = ProductionProperty.PrivateID;
                //TextBoxProductionLabel.Text = HelperClass.ConvertBase64toString(ProductionProperty.Label);
                TextBoxProductionLabel.Text = ProductionProperty.Label;
                TextBlockProductionDeploymentName.Text = ProductionProperty.Name;
                TextBlockProductionStatus.Text = ProductionProperty.Status;

                ImageProduction.Source = new BitmapImage(new Uri("/WpfApplication2;component/images/DeployPic.jpg", UriKind.Relative));
                ProductionUpgrade.Visibility = Visibility.Visible;
                ButtonProductionStatus.Visibility = Visibility.Visible;
                ButtonProductionConfigure.Visibility = Visibility.Visible;
                BtnProductionDelete.Visibility = Visibility.Visible;
                BtnProductionCreateDeploy.Visibility = Visibility.Collapsed;
                BtnProductionRefresh.Visibility = Visibility.Visible;

            }
            else 
            {
                ImageProduction.Source = new BitmapImage(new Uri("/WpfApplication2;component/images/CreateDeploy.jpg",UriKind.Relative));
                TextBlockProductionStatus.Text = "";
                TextBlockProductionDeploymentName.Text = "";
                DataGridProductionRoleList.ItemsSource = null;
                TextBoxProductionURL.Text = ""; ;
                TextBlockProductionID.Text = "";
                TextBoxProductionLabel.Text = "";
                ButtonSwap.Visibility = Visibility.Collapsed;
                BtnProductionCreateDeploy.Visibility = Visibility.Visible;
                ProductionUpgrade.Visibility = Visibility.Collapsed;
                ButtonProductionStatus.Visibility = Visibility.Collapsed;
                ButtonProductionConfigure.Visibility = Visibility.Collapsed;
                BtnProductionDelete.Visibility = Visibility.Collapsed;
                BtnProductionRefresh.Visibility = Visibility.Collapsed;
                
            }
        }

        private void ButtonProductionStatus_Click(object sender, RoutedEventArgs e)
        {
            String Status = String.Empty;
            //StagingProperty.Url.LastIndexOf("/")

            if (ProductionProperty.Status.Equals("Running") || ProductionProperty.Status.Equals("Suspended"))
            {
                if (ProductionProperty.Status.Equals("Running"))
                {
                    if (MessageBox.Show("Are you sure you want to suspend this hosted service ?", "Warning", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
                    {
                        Status = "Suspended";
                        ShowMask();
                        serviceController.UpdateDeploymentStatusAsync(App.SubscriptionID, App.CertificatePath, ServiceName, "Production", Status, null);

                    }
                    
                }
                if (ProductionProperty.Status.Equals("Suspended"))
                {
                    Status = "Running";
                    ShowMask();
                    serviceController.UpdateDeploymentStatusAsync(App.SubscriptionID, App.CertificatePath, ServiceName, "Production", Status, null);  
               
                }
                //if (!String.IsNullOrEmpty(Status))
                //{
                    //ShowMask();
                    //serviceController.UpdateDeploymentStatusAsync(App.SubscriptionID, App.CertificatePath, ServiceName, "Production", Status, null);
                //}
            }
            else 
            {
                MessageBox.Show("No action can be performed at this time. Please try your request in a while.","Information",MessageBoxButton.OK,MessageBoxImage.Information);
                LoadProperties();
            }
           
        }

        private void ButtonStagingStatus_Click(object sender, RoutedEventArgs e)
        {
            String Status = String.Empty;
            //StagingProperty.Url.LastIndexOf("/")
            if (StagingProperty.Status.Equals("Running") || StagingProperty.Status.Equals("Suspended"))
            {
             
                if (StagingProperty.Status.Equals("Running"))
                {
                    if (MessageBox.Show("Are you sure you want to suspend this hosted service ?", "Warning", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
                    {
                        Status = "Suspended";
                        ShowMask();
                        serviceController.UpdateDeploymentStatusAsync(App.SubscriptionID, App.CertificatePath, ServiceName, "Staging", Status, null);

                    }
                }
                if (StagingProperty.Status.Equals("Suspended"))
                {
                    Status = "Running";
                    ShowMask();
                    serviceController.UpdateDeploymentStatusAsync(App.SubscriptionID, App.CertificatePath, ServiceName, "Staging", Status, null);


                }
                //if (!String.IsNullOrEmpty(Status))
                //{
               // ShowMask();
                //serviceController.UpdateDeploymentStatusAsync(App.SubscriptionID, App.CertificatePath, ServiceName, "Staging", Status, null);
                //}
            }
            else 
            {
                MessageBox.Show("No action can be performed at this time. Please try your request in a while.", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                LoadProperties();
            }

        }

        private void BtnStagingConfigure_Click(object sender, RoutedEventArgs e)
        {
            ConfigureWindow configWindow = new ConfigureWindow(StagingProperty,ServiceName);
            configWindow.Owner = Window.GetWindow(this);
            if (configWindow.ShowDialog() == true)
            {
                LoadProperties();
            }

        }

        private void BtnStagingDelete_Click(object sender, RoutedEventArgs e)
        {

            if (MessageBox.Show("Are you sure you want to delete this deployment ?", "Delete Deployment", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
            {
                ShowMask();
                serviceController.DeleteDeploymentAsync(App.SubscriptionID, App.CertificatePath, ServiceName, "Staging", null);
            }
        }

        private void ButtonStagingDeploy_Click(object sender, RoutedEventArgs e)
        {
            UpgradeDeploymentWindow upgradeWindow = new UpgradeDeploymentWindow(StagingProperty,ServiceName);
            upgradeWindow.Owner = Window.GetWindow(this);
            if (upgradeWindow.ShowDialog() == true)
            {
                LoadProperties();
            }

        }

        private void ButtonSwap_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to swap deployments ?","Swap Deployments",MessageBoxButton.YesNo,MessageBoxImage.Warning) == MessageBoxResult.Yes)
            {
                ShowMask();
                serviceController.SwapAsync(App.SubscriptionID, App.CertificatePath, ServiceName, ProductionProperty.Name, StagingProperty.Name, null);
            }
        }

        private void HandleRequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
            e.Handled = true;


        }

        private void ProductionUpgrade_Click(object sender, RoutedEventArgs e)
        {
            UpgradeDeploymentWindow upgradeWindow = new UpgradeDeploymentWindow(ProductionProperty, ServiceName);
            upgradeWindow.Owner = Window.GetWindow(this);
            if (upgradeWindow.ShowDialog() == true)
            {
                LoadProperties();
            }
        }

        private void ButtonProductionConfigure_Click(object sender, RoutedEventArgs e)
        {
            ConfigureWindow configWindow = new ConfigureWindow(ProductionProperty, ServiceName);
            configWindow.Owner = Window.GetWindow(this);
            if (configWindow.ShowDialog() == true)
            {
                LoadProperties();
            }

        }

        private void BtnProductionDelete_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to delete this deployment ?", "Delete Deployment", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
            {
                ShowMask();
                serviceController.DeleteDeploymentAsync(App.SubscriptionID, App.CertificatePath, ServiceName, "Production", null);
            }
        }

        private void BtnStagingCreateDeploy_Click(object sender, RoutedEventArgs e)
        {
            CreateDeployWindow createDeployWindow = new CreateDeployWindow(ServiceName, "Staging");
            //UpgradeDeploymentWindow upgradeWindow = new UpgradeDeploymentWindow(StagingProperty, ServiceName);
            createDeployWindow.Owner = Window.GetWindow(this);
            if (createDeployWindow.ShowDialog() == true)
            {
                LoadProperties();    
            }
        }

        private void BtnProductionCreateDeploy_Click(object sender, RoutedEventArgs e)
        {
            CreateDeployWindow createDeployWindow = new CreateDeployWindow(ServiceName, "Production");
            createDeployWindow.Owner = Window.GetWindow(this);
            if (createDeployWindow.ShowDialog() == true)
            {
                LoadProperties();
            }
        }

        private bool GetOperationStatus()
        {
            if (RequestID != null)
            {
                serviceController.GetOperationStatusAsync(App.SubscriptionID, App.CertificatePath, RequestID, null);
                return false;
            }
            return true;
        }

        private void HideMask()
        {
            startbusy.Stop();
            stopbusy.Begin();
            border2_Copy.Visibility = Visibility.Collapsed;
        }

        private void ShowMask()
        {
            border2_Copy.Visibility = Visibility.Visible;
            startbusy.Begin();
        }

        private void ButtonRefresh_Click(object sender, RoutedEventArgs e)
        {
            LoadProperties();
        }

    }

}
